/*
 * @Author: your name
 * @Date: 2021-02-02 11:43:35
 * @LastEditTime: 2021-02-26 15:48:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \myproject\src\utils\request.js
 */

import axios from 'axios'
import store from '@/store/index.js'
import JSONBig from 'json-bigint' // 引入大数字包
import router from '@/router'
// import store from '@/store'
// 这里通过axios.create来创建多个不同的axios的实例，以备不时之需
const instance = axios.create({
  baseURL: 'http://toutiao-app.itheima.net',
  transformResponse: [function (data) {
    try {
      return JSONBig.parse(data)
    } catch (err) {
      return data
    }
  }]
})
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  // console.log(config)
  // console.log(store.state.tokenInfo.token)
  // const token = store.state.tokenInfo.token
  if (store.state.tokenInfo && store.state.tokenInfo.token) {
    config.headers.Authorization = `Bearer ${store.state.tokenInfo.token}`
  }

  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use((response) => {
  // 对响应数据做点什么
  return response
}, async (error) => {
  // 对响应错误做点什么
  if (error.response.status === 401) {
    // router.push({
    //   path: '/login',
    //   query: {
    //     backto: router.currentRoute.fullPath
    //   }
    // })
    const refreshToken = store.state.tokenInfo.refresh_token
    try {
      const res = await axios({
        method: 'PUT',
        url: 'http://toutiao-app.itheima.net/v1_0/authorizations',
        headers: {
          Authorization: `Bearer ${refreshToken}`
        }
      })
      // console.log(res)
      const newToken = res.data.data.token
      store.commit('setToken', {
        refresh_token: refreshToken,
        token: newToken
      })
      // 重新使用我们之间创建的axios实例，用本次错误请求中的配置项,再发一次
      console.log(error.config)
      return instance(error.config)
    } catch {
      router.push({
        path: '/login',
        query: {
          // currentRoute：表示当前路由
          backto: router.currentRoute.fullPath
        }
      })
    }
  }
  return Promise.reject(error)
})

export default instance
